package com.playwright.util.zhihu2toutiao;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;
import com.microsoft.playwright.options.LoadState;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author liyanhao
 * @Date 2024-01-17 11:13
 */
public class 保存登陆信息 {
    public static void main(String[] args) throws InterruptedException {
        try (Playwright playwright = Playwright.create()) {

            Browser browser = PlaywrightUtils.getBrowser(playwright);

            BrowserContext context = browser.newContext();
            Page page = context.newPage();
            page.navigate("https://mms.pinduoduo.com/login/");

            page.waitForLoadState(LoadState.DOMCONTENTLOADED); // 等待页面完全加载
            Thread.sleep(100000);
            //等到热榜出现
//            page.getByRole(AriaRole.MAIN).getByRole(AriaRole.LINK, new Locator.GetByRoleOptions().setName("热榜")).click();

            // 3. 保存认证后的浏览器状态
            String statePath = Paths.get("C:\\auth\\state_pdd.json").toString();
            BrowserContext.StorageStateOptions options = new BrowserContext.StorageStateOptions();
            options.setPath(Paths.get(statePath));
            context.storageState(options);

            context.close();
            browser.close();
        }




        // 在另一个测试或执行中加载保存的状态
        try (Playwright playwright = Playwright.create()) {
            BrowserType.LaunchOptions launchOptions = new BrowserType.LaunchOptions();


            launchOptions.setExecutablePath(Path.of("C:\\Users\\lyh\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"));
            launchOptions.setHeadless(false).setSlowMo(500);
            Browser browser = playwright.chromium().connectOverCDP("http://localhost:9222");

            // 3. 保存认证后的浏览器状态
            String statePath = Paths.get("C:\\auth\\state_pdd.json").toString();
            BrowserContext.StorageStateOptions options = new BrowserContext.StorageStateOptions();
            options.setPath(Paths.get(statePath));
            // 加载之前保存的浏览器状态以保持登录状态
            BrowserContext context = browser.newContext(new Browser.NewContextOptions()
                    .setStorageStatePath(Paths.get(statePath)));

            Page page = context.newPage();
            page.navigate("https://mms.pinduoduo.com/home");
            Thread.sleep(100000);
            // ... 进行其他测试操作 ...

            context.close();
            browser.close();
        }
    }


}
